//
//  User.swift
//  JLDiaryApp
//
//  Created by Jiang Chencheng on 2024/9/25.
//

import Foundation
import SwiftUI
import Moya

class UserCenter: ObservableObject {

    let provider = MoyaProvider<UserService>()
    
    init() {
        self.token = UserDefaults.standard.string(forKey: "kJLTokenKey") ?? ""
        self.user = try? StorageCenter.get(key: UserModel.key)
    }
    
    @Published var token: String = "" {
        didSet {
            UserDefaults.standard.setValue(token, forKey: "kJLTokenKey")
        }
    }
    
    @Published var user: UserModel? {
            
        didSet {
            
            do {
                try StorageCenter.save(value: user)
            } catch {
                print("\(error)")
            }
        }
        
    }
    
}

extension UserCenter {
    
    /// 是否登录
    var isLogin: Bool {
        token.isEmpty
    }
    
    
    /// 注册
    /// - Parameters:
    ///   - email: 邮箱
    ///   - password: 密码
    func signup(email: String, password: String) async throws {
        let result: AccessTokenModel = try await provider.request(.signup(email: email, password: password))
        token = result.token
        user = result.user
    }
    
    
    /// 登录
    /// - Parameters:
    ///   - email: 邮箱
    ///   - password: 密码
    func signin(email: String, password: String) async throws {
        let result: AccessTokenModel = try await provider.request(.signin(email: email, password: password))
        token = result.token
        user = result.user
    }
    
    
    /// 退出登录
    func signout() async throws {
        token = ""
        user = nil
    }
    
}
